package com.plat.common;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

public class UmsConfig {
	private static Logger log = Logger.getLogger(UmsConfig.class);									//log4j日志
	
	public final static String PROP_PWD = "/../system-cfg/";										//配置文件路径
	public final static String PROP_SYSTEM = PROP_PWD + "ums.properties";							//全局配置文件

	private static Map<String, Properties> propertieMap = new HashMap<String, Properties>();
	private static Map<String, String> propertieFileMap = new HashMap<String, String>();

	static {
		Properties properties = init(PROP_SYSTEM);
		Iterator<?> it = properties.keySet().iterator();
		properties.getProperty("path");

		while (it.hasNext())
		{
			String name = (String) it.next();
			String file = properties.getProperty(name);

			file = file.trim();

			propertieFileMap.put(name, file);
			Properties p = init(PROP_PWD + file);
			propertieMap.put(name, p);
		}
	}
	
	private static Properties init(String propertyFile) {
		Properties p = new Properties();
		try {
			log.info("Start Loading property file \t" + propertyFile);
			p.load(new InputStreamReader(UmsConfig.class.getResourceAsStream(propertyFile), "UTF-8"));
			log.info("Load property file success!\t" + propertyFile);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("Could not load property file." + propertyFile, e);
		}

		return p;
	}
	
	public static String getProperty(String cls, String name) {
		Properties p = (Properties) propertieMap.get(cls);
		if (p != null) {
			return p.getProperty(name);
		} else {
			return null;
		}
	}

	public static boolean getBooleanProperty(String cls, String name) {
		String p = getProperty(cls, name);
		return "true".equals(p);
	}

	public static Integer getIntegerProperty(String cls, String name) {
		String p = getProperty(cls, name);
		if (p == null) {
			return null;
		}
		return Integer.valueOf(p);
	}

	public static Long getLongProperty(String cls, String name) {
		String p = getProperty(cls, name);
		if (p == null) {
			return null;
		}
		return Long.valueOf(p);
	}

	public static Double getDoubleProperty(String cls, String name) {
		String p = getProperty(cls, name);
		if (p == null) {
			return null;
		}
		return Double.valueOf(p);
	}

	public static void store() {
	}

	public static void store(String cls) {
		Properties p = (Properties) propertieMap.get(cls);
		FileOutputStream fi;
		try {
			fi = new FileOutputStream(
					new File(
							(String) propertieFileMap.get(cls)
							)
					);
			p.store(fi, "Modified time: " + Calendar.getInstance().getTime());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
